let d = new Date();

let nowYear = d.getFullYear(),
  nowYearCount = 0,
  nowMonth = d.getMonth() + 1,
  nowMonthCount = 0,
  quarter,
  quarterCount = 0,
  nowDate = d.getDate();
// 今天
let today =
  nowYear +
  "-" +
  (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
  "-" +
  (nowDate < 10 ? "0" + nowDate : nowDate);
// console.log(today);
// 本月团队签约数据
let teamNowMonthData = [];
// 7天内数据
let sevenData = [];
// 本季度包括的月份
switch (nowMonth) {
  case 1:
  case 2:
  case 3:
    quarter = [1, 2, 3];
    break;
  case 4:
  case 5:
  case 6:
    quarter = [4, 5, 6];
    break;
  case 7:
  case 8:
  case 9:
    quarter = [7, 8, 9];
    break;
  case 10:
  case 11:
  case 12:
    quarter = [10, 11, 12];
    break;
}

window.onload = function () {
  $.ajax({
    url: "/doctor/count",
    success(res) {
      if (res.code === 0) {
        // console.log(res.data);
        $("#doctorCount").text(res.data[0].count);
      }
    },
  });
  $.ajax({
    url: "/team/all",
    success(res) {
      if (res.code === 0) {
        // console.log(res.data);
        $("#teamCount").text(res.data.length);
      }
    },
  });
  $.ajax({
    url: "/residents/statistical",
    success(res) {
      if (res.code === 0) {
        // console.log(res.data);
        let uniRidArr = []; //兑换唯一RID
        let uniResidentsArr = []; // 兑换唯一的数据
        res.data.forEach((item) => {
          if (!uniRidArr.includes(item.rid)) {
            // 判断一下是否包含了？
            uniRidArr.push(item.rid);
            uniResidentsArr.push(item);
          }
        });
        console.log(uniResidentsArr);

        uniResidentsArr.forEach((item) => {
          // 全年签约数据
          if (nowYear.toString() === item.date.slice(0, 4)) {
            nowYearCount++;
          }
          // 本月签约数据
          if (nowMonth === Number(item.date.slice(5, 7))) {
            nowMonthCount++;
            teamNowMonthData.push(item);
          }
          // 本季度签约数据
          if (quarter.includes(Number(item.date.slice(5, 7)))) {
            quarterCount++;
          }
          // 今日新签约居民数据
          if (today === item.date) {
            $("#nowList").append(
              `<li class="list-group-item">${item.rname}-${
                nowYear - item.rsid.slice(6, 10)
              }岁</li>`
            );
          }
          // 7天内的数据 sevenData
          // console.log(1000*60*60*24*7);
          // console.log(Date.parse(item.date));
          if (
            Date.parse(item.date) <= Date.parse(today) &&
            Date.parse(item.date) >= Date.parse(today) - 1000 * 60 * 60 * 24 * 7
          ) {
            sevenData.push(item);
          }
        });
        console.log(sevenData);

        $("#yearCount").text(nowYearCount);
        $("#monthCount").text(nowMonthCount);
        $("#qutarterCount").text(quarterCount);
        // 统计每个团队的签约数据
        let teamTempData = [];
        teamNowMonthData.forEach((el) => {
          // 合成新的数组
          let obj = { tid: el.tid, tname: el.tname, count: 1 };

          if (
            !teamTempData.some((item) => {
              return item.tid === obj.tid;
            })
          ) {
            teamTempData.push(obj);
          } else {
            teamTempData.forEach((item) => {
              if (item.tid === obj.tid) {
                item.count++;
              }
            });
          }
        });
        // console.log(teamTempData);
        // 本月各团队签约数据
        teamTempData.sort(function (a, b) {
          return b.count - a.count; // 降序
        });
        teamTempData.forEach((el) => {
          $("#weekList")
            .append(`<li class="list-group-item d-flex justify-content-between align-items-center">
          ${el.tname}
          <span class="badge badge-success badge-pill">${el.count}</span>
        </li>`);
        });
        // 冠军团队
        if (teamTempData.length === 0) {
          $("#winTeam").text("暂无");
        } else {
          $("#winTeam").text(teamTempData[0].tname);
        }

        // 连续7天数据
        draw1(sevenData);
      }
    },
  });
};

// canvas
async function draw1(arr) {
  var chartDom = document.getElementById("canvas1");
  var myChart = echarts.init(chartDom);
  var option;
  let teamName = [];
  let tempArr = [];
  arr.forEach((item) => {
    tempArr.push(item.tname);
  });
  teamName = await Array.from(new Set(tempArr));
console.log(teamName);
  // 求7天的日期
  let sevenDay = [];
  let servenDay2 = []
  // console.log(new Date().toLocaleDateString());
  let oneTime = 1000 * 60 * 60 * 24;
  let time = Date.parse(new Date().toLocaleDateString())+oneTime;

  
  for (let i = 1; i <= 7; i++) {
    // console.log(time - oneTime * i);
    let d = new Date(time - oneTime * i);
    let y = d.getFullYear();
    let m = d.getMonth() + 1;
    let day = d.getDate();

    let everyDayStr = y + "-" + checkDate(m) + "-" + checkDate(day);
    sevenDay.push(everyDayStr);
    servenDay2.push(checkDate(m) + "-" + checkDate(day))
  }
  console.log(sevenDay);

  let seriesArr = [];
// 渲染每个团队的7天连续数据
  teamName.forEach((el,index) => {
    // 一个团队，一个对象
    seriesArr.push({
      name: el, //设置团队名字
      type: "line",
      stack: "Total",
      smooth: true,
      lineStyle: {
        width: 0,
      },
      showSymbol: false,
      areaStyle: {
        opacity: 0.8,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: "rgb(128, 255, 165)",
          },
          {
            offset: 1,
            color: "rgb(1, 191, 236)",
          },
        ]),
      },
      emphasis: {
        focus: "series",
      },
      data: [],
    })
   
    sevenDay.forEach((item) => {
      
      let arrTemp =[]
       arrTemp = arr.filter((item2)=>{
        return item2.tname === el && item2.date === item;
      })
      // 把一天中所有数据的个数，添加到目标数组。
      seriesArr[index].data.push(arrTemp.length)
    });
  });
// console.log(seriesArr);

  option = {
    color: ["#80FFA5", "#00DDFF", "#37A2FF", "#FF0087", "#FFBF00"],
    // title: {
    //   text: 'Gradient Stacked Area Chart'
    // },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985",
        },
      },
    },
    legend: {
      data: teamName,
    },
    toolbox: {
      feature: {
        saveAsImage: {},
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        boundaryGap: false,
        data: servenDay2,
      },
    ],
    yAxis: [
      {
        type: "value",
      },
    ],
    series: seriesArr
    // [
    //   {
    //     name: "天字一号",
    //     type: "line",
    //     stack: "Total",
    //     smooth: true,
    //     lineStyle: {
    //       width: 0,
    //     },
    //     showSymbol: false,
    //     areaStyle: {
    //       opacity: 0.8,
    //       color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    //         {
    //           offset: 0,
    //           color: "rgb(128, 255, 165)",
    //         },
    //         {
    //           offset: 1,
    //           color: "rgb(1, 191, 236)",
    //         },
    //       ]),
    //     },
    //     emphasis: {
    //       focus: "series",
    //     },
    //     data: [14, 23, 1, 24, 9, 30, 20],
    //   },
    //   {
    //     name: "天字二号",
    //     type: "line",
    //     stack: "Total",
    //     smooth: true,
    //     lineStyle: {
    //       width: 0,
    //     },
    //     showSymbol: false,
    //     areaStyle: {
    //       opacity: 0.8,
    //       color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    //         {
    //           offset: 0,
    //           color: "rgb(0, 221, 255)",
    //         },
    //         {
    //           offset: 1,
    //           color: "rgb(77, 119, 255)",
    //         },
    //       ]),
    //     },
    //     emphasis: {
    //       focus: "series",
    //     },
    //     data: [40, 32, 10, 26, 9, 34, 25],
    //   },
    // ]
    ,
  };

  option && myChart.setOption(option);
}

// 日期补零
function checkDate(v) {
  return v < 10 ? "0" + v : v;
}
